package com.yunc.modules.cms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.yunc.common.utils.R;
import com.yunc.modules.cms.entity.QuestionSubject;
import com.yunc.modules.cms.entity.QuestionSubjectSelect;
import com.yunc.modules.cms.mapper.QuestionSubjectMapper;
import com.yunc.modules.cms.service.IQuestionSubjectSelectService;
import com.yunc.modules.cms.service.IQuestionSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 问卷题目表 service实现
 *
 * @author concong tao
 * @since 2019-01-31
 */
@Service
public class QuestionSubjectServiceImpl extends ServiceImpl<QuestionSubjectMapper, QuestionSubject> implements IQuestionSubjectService {

    @Autowired
    private IQuestionSubjectSelectService questionSubjectSelectService;

    @Override
    public R saveQuestionSubject(Long questionId, String subjectJson) {
        // 转为subject
        List<QuestionSubject> subjectList = JSONArray.parseArray(subjectJson, QuestionSubject.class);
        // 分别保存
        if (subjectList == null || subjectList.size() == 0) {
            return R.ok();
        }
        List<QuestionSubjectSelect> subjectSelectList = new ArrayList<>();
        for (QuestionSubject subject : subjectList) {
            // 保存，并获取到主键，然后分别保存
            subject.setQuestionId(questionId);
            subject.setCreateTime(new Date());
            boolean subjectFlag = this.save(subject);
            if (!subjectFlag) {
                continue;
            }
            List<QuestionSubjectSelect> selectList = subject.getSelectList();
            if (selectList == null || selectList.size() == 0) {
                continue;
            }
            Long subjectId = subject.getId();
            // 获取到A,B
            char numStr = 'A';
            for (QuestionSubjectSelect subjectSelect : selectList) {
                subjectSelect.setNum(String.valueOf(numStr));
                subjectSelect.setQuestionId(questionId);
                subjectSelect.setSubjectId(subjectId);
                subjectSelectList.add(subjectSelect);
                numStr++;
            }
        }
        int info = questionSubjectSelectService.insertList(subjectSelectList);
        if (info <= 0) {
            return R.error();
        }
        return R.ok();
    }
}
